/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package viewer.mortgage;

/**
 *
 * @author karakots
 */


import Household.Household;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.event.*;

import javax.swing.JFrame;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import javax.swing.Box;
import javax.swing.BorderFactory;
import javax.swing.JPanel;

import Bank.Bank;
import MortgageCore.*;
import viewer.common.Trans2D;

public class HouseholdMCView extends MCMapObj {
    // knows how to draw houshold
    final Household hh;
    boolean statusDialogOpen;
    JDialog dialog;
    JLabel infoDialogLabel;
    JLabel logLabel;
    private boolean showHome;
    HomeHistory hhl;

    // constructor
    public HouseholdMCView (Household hh, Trans2D trans) {
        this.hh = hh;
        setMapImageRect(hh.getLoc().getX(), hh.getLoc().getY(), trans);
        statusDialogOpen = false;
        showHome = true;
    }

    public void setShowHome(boolean s) {
        showHome= s;
    }
    
    public void drawMapImage(Graphics2D g, double scale, boolean drawHomeowners, boolean drawRenters) {
        if (!drawHomeowners && hh.hb().getIsHomeowner())
            return;
        if (!drawRenters && !(hh.hb().getIsHomeowner()))
            return;
        
        boolean isSelected = hh.getSelected();
        boolean isEvaluatingToday = hh.isEvaluatingToday();

        if (isSelected) {
            drawLinkToBank(g, scale);
           // drawHouse(g, scale, IconColor.kRed);
        } /*else if (isEvaluatingToday) {
            if (showHome) {
                drawHouse(g, IconColor.kYellow);
            }
        } else {
            if (showHome) {
                drawHouse(g, IconColor.kBlue);
            }
        }
        */

        if (!hh.hb().getIsHomeowner()) {
            if (showHome)
                drawRenter(g, scale);
        } else {
            if (hh.hb().hasActiveMortgageRequest())
                drawDiamond(g, scale, IconColor.kBlack);
            else if (hh.hb().getHasPreApprovedLoan())
                drawDiamond(g, scale, IconColor.kWhite);
            else if (hh.hb().getIsHomeowner())
                drawFundedMortgageState(g, scale);

        if (hh.hb().getMissedPaymentLastMonth())
            drawExclaim(g, scale);
        if (hh.hb().getTryingToMove())
            drawPlus(g, scale);
        }

        if (statusDialogOpen) {
            String infoString = CreateInfoString();
            infoDialogLabel.setText(infoString);
        }

        if (hh.logViewOpen) {
            String logStr = CreateHHLogString();
            logLabel.setText(logStr);
        }
    }

    private void drawFundedMortgageState(Graphics g, double scale) {
        int size =  (int) (12/scale + 0.5);
        double pctPaid;
        if (hh.hb().getMortgage() == null)
            pctPaid = 1;
        else
            pctPaid = hh.hb().getMortgage().getPctPaid();
        int x = loc.x;// + 3;
        int y = loc.y;// + 6;
        if (pctPaid > 0.99999)
            g.drawImage(blueDiamond.getImage(), x, y, size, size, null);
        else if (pctPaid > 0.8)
            g.drawImage(greenDiamond.getImage(), x, y, size, size, null);
        else if (pctPaid > 0.6)
            g.drawImage(greenDiamond80.getImage(), x, y, size, size, null);
        else if (pctPaid > 0.4)
            g.drawImage(greenDiamond60.getImage(), x, y, size, size, null);
        else if (pctPaid > 0.2)
            g.drawImage(greenDiamond40.getImage(), x, y, size, size, null);
        else
            g.drawImage(greenDiamond20.getImage(), x, y, size, size, null);
    }

    private void drawLinkToBank(Graphics2D g, double scale) {
        Bank savingsBank = hh.getSavingsBank();
        if (savingsBank != null) {
            int size =  (int) (12/scale + 0.5);
            int x0, y0, x1, y1;
            x0 = (int) hh.getLoc().getX()-size/2;
            y0 = (int) hh.getLoc().getY()+size/2;
            x1 = (int) savingsBank.getLoc().getX()-size/2;
            y1 = (int) savingsBank.getLoc().getY()+size/2;
            double d = (double) hh.getDaysSinceLastEval();
            double dayFactor;
            // if within 15 days, ramp green down
            if (d < 15.0)
                dayFactor = ((15.0-d) / 15.0);
            // otherwise, ramp green up
            else
                dayFactor = ((d-15.0) / 15.0);
            // convert from linear to nonlinear ramp;
            dayFactor = Math.pow(dayFactor,5);
            float alpha = (float) (0.1 + (dayFactor*0.9));
            Color lineColor = new Color(0, 1, 0, alpha);
            g.setColor(lineColor);

            // to draw an antialiased line, use Java2D
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.drawLine(x0, y0, x1, y1);
        }
    }
    
    public boolean hit(Point p, double scale, boolean multipleSelected, boolean drawHomeowners, boolean drawRenters) {
        if (!drawHomeowners && hh.hb().getIsHomeowner())
            return false;
        if (!drawRenters && !(hh.hb().getIsHomeowner()))
            return false;
        
        boolean selected;
        boolean wasSelected = hh.getSelected();
        int size =  (int) (12/scale + 0.5);
        if (multipleSelected && wasSelected) {
            if (checkHit(p, size)) {
                hh.setSelected(!wasSelected);
            }
            selected = hh.getSelected();
        } else {
            selected = checkHit(p, size);
            hh.setSelected(selected);
        }
        if (selected) { // (selected && !wasSelected) {
            if (dialog != null)
                dialog = null;
            CreateInfoWindow();
        } //else if (!selected && wasSelected) {
         //   ;
        //}
        return selected;
    }

    public String CreateHHLogString() {
        String labelText = new String ("<html><p align=left><b>" + "Household Log</b><br><hr/>");

        for(String s : hh.hb().mortgageRecord) {
            labelText = labelText.concat(s + "<br>");
        }
        return labelText;
    }

    public String CreateInfoString() {
        int incomePct = (int) (hh.getIncomePctMedian() * 100);
        String labelText = new String(
                "<html><p align=left><b>" + "Household Info</b><br><hr/>" +
                "State = " + hh.getCityName() + ", " + hh.getStateName() + "<br>"
                );
        if (hh.getNumPeople() == 1) {
            labelText = labelText.concat(hh.getFamilyStatus() + ", " + hh.getNumPeople() + " person" + "<br>" +
                    "Income % of median = " + incomePct + "%<br>");
        } else {
            labelText = labelText.concat(hh.getFamilyStatus() + ", " + hh.getNumPeople() + " people" + "<br>" +
                    "Income % of median = " + incomePct + "%<br>");
        }
        if (hh.hb().getIsHomeowner()) {
            int price =  (int) hh.hb().getHomePurchasePrice()/1000;
            labelText = labelText.concat("Homeowner <br>" +
                     "Purchase price = $" + price + "K<br><br>");
        } else {
            labelText = labelText.concat("Renter <br><br>");
        }
        double balance = hh.getSavings();
        labelText = labelText.concat("Monthly Finances</b><br><hr/>" +
                "Salary = $" + ((int) hh.getMonthlySalary()) + "<br>" +
                "Expenses = $" + ((int) hh.getExpenses()) + "<br>"
                );
        Mortgage mtg = hh.hb().getMortgage();
        int mortgagePayment = 0;
        if (mtg != null) {
            mortgagePayment = (int) mtg.getMonthlyPayment();
            labelText = labelText.concat("Mortgage Payment = $" + mortgagePayment + "<br>");
        } else if (!hh.hb().getIsHomeowner()) {
            int rent = (int) hh.hb().getRent();
            labelText = labelText.concat("Rent = $" + rent + "<br>");
        }
        labelText = labelText.concat("Cash = $" + ((int) hh.getcashAssets()) + "<br>" +
                "Savings = $" + ((int) balance) + "<br>" +
                "Savings Rate = " + ((int) (hh.getSavingsRate() * 100.0)) + "%<br> <br>" +
                "<b>Mortgage Info</b><br><hr/>");
        // home ownership
        // house purchase price
        /*
        switch(hh.getMortgageState()) {
            case NOMORTGAGE:
                labelText = labelText.concat("No mortgage<br>");
                break;
            case REQUESTOUT:
                labelText = labelText.concat("Requesting a mortgage<br>");
                break;
            case PREAPPROVED:
                labelText = labelText.concat("Has preapproved mortgage<br>");
                break;
            case FUNDED:
                labelText = labelText.concat("Mortgage is funded<br>");
                break;
             case PAIDINFULL:
                labelText = labelText.concat("Mortgage paid off!<br>");
                break;
           case INDEFAULT: {
                int numMissedPayments = hh.getNumMissedMortgagePayments();
                if (numMissedPayments == 1)
                    labelText = labelText.concat("Mortgage in default<br>" + "Missed " + numMissedPayments + " payment<br>");
                else
                    labelText = labelText.concat("Mortgage in default<br>" + "Missed " + numMissedPayments + " payments<br>");
                break;
            }
        }
        */
        // number of times applid for a mortgage
        int numMorgageApps = hh.hb().getNumMortgageApps();
        if (numMorgageApps > 1)
            labelText = labelText.concat(numMorgageApps + " Mortgage applications<br>");
        else if (numMorgageApps == 1)
             labelText = labelText.concat(numMorgageApps + " Mortgage application<br>");

        if (hh.hb().getMaxLengthUtil() > hh.hb().getMinLengthUtil())
            labelText = labelText.concat("Prefers " + hh.hb().getMaxLength() + " year mortgage <br>");
        else
            labelText = labelText.concat("Prefers " + hh.hb().getMinLength() + " year mortgage <br>");
        if (hh.hb().getMinFixedRateUtil() > hh.hb().getMaxFixedRateUtil())
            labelText = labelText.concat("Prefers variable rate <br>");
        else
            labelText = labelText.concat("Prefers fixed rate <br>");

        // current mortgage State
        if (mtg != null) {
            MortgageTerms mt = mtg.getTerms();
            //Aount Borrowed
            int amountBorrowed = (int) (mtg.getFundedAmount()/1000);
            // amount paid
            double pctPaid = mtg.getPctPaid() * 100;
            String pctPaidStr = String.format("%2.2f",pctPaid);
            // % downpayment
            int pctDownPayment = (int) (mt.getMinDownPayment() * 100);
            // term
            int loanTerm = mt.getLengthInYears();
            // interest rate
            double interestRate = mt.getMonthlyInterestRate() * 12;
            String interestRateStr = String.format("%2.2f",(interestRate * 100));
            // payment/income ratio
            int paymentToIncome = (int) (100 * mortgagePayment / hh.getMonthlySalary());
            labelText = labelText.concat(
                    "<br>" + pctDownPayment + "% Down Payment<br>" +
                     loanTerm + " Year Loan at " + interestRateStr + "% Interest<br>" +
                    "$" + amountBorrowed + "K borrowed, " + "<br>" +
                    pctPaidStr + "% Repaid<br>" +
                    "Payment to Income ratio = " + paymentToIncome + "%"
                    );
        }


        return labelText;
    }

    public void CreateInfoWindow() {
        statusDialogOpen = true;
        final JFrame frame = new JFrame("DialogDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Create the dialog.
        // get the number of the HH
        dialog = new JDialog(frame,"HH@ X=" + (int) hh.getLoc().getX() + " Y=" + (int) hh.getLoc().getY());
        //a nice tan background
        dialog.setBackground(new Color(0.816f, 0.937f, 1.0f));

        //Add contents to it.
        infoDialogLabel = new JLabel(CreateInfoString());
        infoDialogLabel.setHorizontalAlignment(JLabel.CENTER);
        Font font = infoDialogLabel.getFont();
        infoDialogLabel.setFont(infoDialogLabel.getFont().deriveFont(font.PLAIN,10.0f));

        //It must have a close button,
        //since some L&Fs (notably Java/Metal) don't provide one
        //in the window decorations for dialogs.
        JButton closeButton = new JButton("Close");
        closeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (hh.logViewOpen) {
                    hhl.setVisible(false);
                    hhl.dispose();
                    hhl = null;
                    hh.logViewOpen = false;
                }
                dialog.setVisible(false);
                dialog.dispose();
                dialog = null;
                statusDialogOpen = false;
            }
        });

        JButton logButton = new JButton("Log");
        logButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (!hh.logViewOpen) {
                    hhl = new HomeHistory();
                    hhl.hh = hh;
                    String titleStr = new String(hh.getCityName() + " " + hh.getStateName());
                    hhl.setTitle(titleStr);
                    hhl.setLocationRelativeTo(frame);
                    hhl.setVisible(true);
                    hhl.setBackground(new Color(0.816f, 0.937f, 1.0f));
                    hh.logViewOpen = true;
                    logLabel = hhl.logLabel;
                }
            }
        });

        

        JPanel closePanel = new JPanel();
        closePanel.setLayout(new BoxLayout(closePanel,BoxLayout.LINE_AXIS));
        closePanel.add(Box.createHorizontalGlue());
        closePanel.add(logButton);
        closePanel.add(Box.createHorizontalGlue());
        closePanel.add(closeButton);
        closePanel.add(Box.createHorizontalGlue());
        closePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 5));

        JPanel contentPane = new JPanel(new BorderLayout());
        contentPane.add(infoDialogLabel, BorderLayout.CENTER);
        contentPane.add(closePanel, BorderLayout.PAGE_END);
        dialog.setContentPane(contentPane);

        //Show it.
        dialog.setSize(new Dimension(200, 420));
        dialog.setLocationRelativeTo(frame);
        // make each one a bit offset rom the others
        Point dLoc = dialog.getLocation();
        double offset;
        offset = -50 + 100*Math.random();
        dLoc.x = (int) (dLoc.getX() + offset);
        offset = -50 + 100*Math.random();
        dLoc.y = (int) (dLoc.getY() + offset);
        dialog.setLocation(dLoc);
        dialog.setVisible(true);
        if (!hh.hb().getEnableLogData())
            logButton.setEnabled(false);
    }

}
